<?php
/**
 * Created by PhpStorm.
 * User: maqun
 * Date: 2016/2/27
 * Time: 16:56
 */
class ContestModel extends BaseModel{

    protected $tableName = "contest";//数据库表名

    #新增竞赛&作业
    public function addContest($post){

        $data   = $this->returnInsert($post);
        $return = array('status'=>'','info'=>'');

        //开启事务
        $this->startTrans();
        if($this->create($data)){
            $cid = $this->add($data);
            if($cid){

                $contestModel   = D('ContestProblem');
                $problemModel   = D('Problem');
                $privilegeModel = M('Privilege');

                //向contest里插入数据并更新problem的defunct
                $plist = explode(",",$post['problems']);
                if (count($plist)>0 && strlen($plist[0])>0){
                    $insert = array();
                    foreach($plist as $key=>$val){
                        $insert[] = array('problem_id'=>$val,'contest_id'=>$cid,'title'=>'','num'=>$key);
                    }
                    $res1 = $contestModel->addAll($insert);
                    $res2 = $problemModel->where("problem_id in(".$post['problems'].")")->save(array('defunct'=>'N'));
                }

                //向表rightstr插入数据
                $res3 = $privilegeModel->where("rightstr='c$cid'")->delete();

                $res4 =$privilegeModel->add(
                                    array(
                                        'user_id'=>$_SESSION['USER']['user_id'],
                                        'rightstr'=>"m$cid"
                                    )
                                );

                $_SESSION["m$cid"]=true;
                $pieces = explode("\n", trim($post['ulist']));
                $res5   = true;
                if (count($pieces)>0 && strlen($pieces[0])>0){
                    foreach($pieces as $k=>$v){
                        $insert[] = array('user_id'=>trim($pieces[$k]),'rightstr'=>"'c$cid'");
                    }
                    $res5 = $privilegeModel->addAll($insert);
                }

                $is_success = $res1 && false!==$res2 && false!==$res3 && $res4 && $res5;

                if($is_success){
                    $this->commit();
                    return array('status'=>true,'info'=>'操作成功');
                }
            }
        }
        $this->rollback();
        return array('status'=>false,'info'=>'操作失败');
    }
    #复制竞赛&作业
    public function copyContest($cid){
        $cid = intval($cid);

        $res = $this->where('contest_id='.$cid)->select();
        if(empty($res)){
            return array('status'=>false,'info'=>'所复制的数据不存在');
        }

        $title           = $res[0]['title'];
        $conproblemModel = D('ContestProblem');

        $result = $conproblemModel->field('problem_id')
                        ->where('contest_id='.$cid)
                        ->order('num desc')
                        ->select();
        $plist="";
        if(!empty($result)){
            foreach($result as $k=>$v){
                $plist .= $k==(count($result)-1) ? $v['problem_id']:$v['problem_id'].',';
            }
        }
        return array('status'=>true,'info'=>array('title'=>$title,'plist'=>$plist));
    }

    #编辑竞赛&作业
    public function editContest($post){

        $data   = $this->returnInsert($post);
        $return = array('status'=>'','info'=>'');

        //开启事务
        $this->startTrans();
        if($this->create($data)){
            $res = $this->where('contest_id='.$data['contest_id'])->save($data);
            if(false!==$res){

                $contestModel   = D('ContestProblem');
                $problemModel   = D('Problem');
                $privilegeModel = M('Privilege');
                $solutionModel  = M('Solution');


                //删除contest_problem中的数据
                $res1 = $contestModel->where('contest_id='.$cid)->delete();

                //向contest_problem里插入数据并更新problem的defunct
                $plist = explode(",",$post['problems']);
                if (count($plist)>0 && strlen($plist[0])>0){
                    $insert = array();
                    foreach($plist as $key=>$val){
                        $insert[] = array('problem_id'=>$val,'contest_id'=>$cid,'title'=>'','num'=>$key);
                    }
                    $res2 = $contestModel->addAll($insert);
                    $solutionModel->where('contest_id='.$cid)->save(array('num'=>-1));

                    $res2 = $problemModel->where("problem_id in(".$post['problems'].")")->save(array('defunct'=>'N'));
                }

                //向表rightstr插入数据
                $res3 = $privilegeModel->where("rightstr='c$cid'")->delete();

                $res4 =$privilegeModel->add(
                    array(
                        'user_id'=>$_SESSION['USER']['user_id'],
                        'rightstr'=>"m$cid"
                    )
                );

                $_SESSION["m$cid"]=true;
                $pieces = explode("\n", trim($post['ulist']));
                $res5   = true;
                if (count($pieces)>0 && strlen($pieces[0])>0){
                    foreach($pieces as $k=>$v){
                        $insert[] = array('user_id'=>trim($pieces[$k]),'rightstr'=>"'c$cid'");
                    }
                    $res5 = $privilegeModel->addAll($insert);
                }

                $is_success = $res1 && false!==$res2 && false!==$res3 && $res4 && $res5;

                if($is_success){
                    $this->commit();
                    return array('status'=>true,'info'=>'操作成功');
                }
            }
        }
        $this->rollback();
        return array('status'=>false,'info'=>'操作失败');
    }
    public function insertContest($cids){

    }
    #返回添加数据
    protected function returnInsert($data){

        $langmask=0;
        if(!empty($data['language'])){
            foreach($data['language'] as $t){
                $langmask += 1<<$t;
            }
            $langmask=1023&(~$langmask);
        }
        $return = array(
            'contest_id'   => !empty($data['contest-id']) ? intval($data['contest-id']): null,
            'title'        => !empty($data['title']) ?  $data['title'] : '',
            'start_time'   => !empty($data['start-time']) ? date('Y-m-d H:i:s',strtotime($data['start-time'])): date('Y-m-d H:i:s',time()),
            'end_time'     => !empty($data['end-time']) ? date('Y-m-d H:i:s',strtotime($data['end-time'])): date('Y-m-d H:i:s',time()),
            'defunct'      => !empty($data['defunct']) ? $data['defunct'] : 'N',
            'description'  => !empty($data['description']) ? addslashes($data['description']): '',
            'private'      => !empty($data['private']) ? intval($data['private']): 0,
            'langmask'     => $langmask
        );
        return $return;
    }
}